package persistencia;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import busqueda.criterio.CriterioCompuesto;


public abstract class IntermediarioRelacional extends IntermediarioPersistencia {
	
	private static String url = "jdbc:mysql://localhost:3306/";
	private static String dbName = "disenio";
	private static String driver = "com.mysql.jdbc.Driver";
	private static String userName = "root";
	private static String password = "";
	public IntermediarioRelacional(String entidad){
		super(entidad);
	}
	public List<Object> materializar(CriterioCompuesto criterio) {
		List<Object> returnObject = new ArrayList<Object>();
		try {
			Connection conn = getConnection();
			String consulta = armarConsultaConCriterio(criterio);
			ResultSet result = conn.createStatement().executeQuery(consulta);
			returnObject = procesarColleccionResultado(result);
			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return returnObject;
		
	}
	public ObjectoPersistente materializar(Long id) {
		ObjectoPersistente returnObject = null;
		try {
			Connection conn = getConnection();
			String consulta = armarConsultaConId(id);
			ResultSet result = conn.createStatement().executeQuery(consulta);
			returnObject = procesarUnResultado(result);
			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return returnObject;
		
	}
	private Connection getConnection() throws Exception{
		Class.forName(driver).newInstance();
		Connection conn = DriverManager.getConnection(url+dbName,userName,password);
		return conn;
	}
	
	private ObjectoPersistente procesarUnResultado(ResultSet result) throws SQLException{
		ObjectoPersistente returnObject = null;
		boolean isEmpty = true;
		while(result.next()) {
			isEmpty = false;
			break;
		}
		if(!isEmpty) returnObject = convertirAObjeto(result);
		return returnObject;
	}
	
	private List<Object> procesarColleccionResultado(ResultSet result) throws SQLException{
		List<Object> returnObject = new ArrayList<Object>();
		while(result.next()) {
			returnObject.add(convertirAObjeto(result));
		}
		return returnObject;
	}
	private String armarConsultaConCriterio(CriterioCompuesto criterio){
		String consulta = "select * from "+this.entidad+" where ";
		for(int i=0;i<criterio.length();i++){
			consulta += criterio.getCriterio(i).getAtributo() + " " + criterio.getCriterio(i).getOperador() + " "+ agregarComillas(criterio.getCriterio(i).getValor());
		}
		consulta += ";";
		return consulta;
	}
	private String armarConsultaConId(Long id){
		String consulta = "select * from "+this.entidad+" where id="+id;
		consulta += ";";
		return consulta;
	}
	private String agregarComillas(String valor){
		return "'"+valor+"'";
	}
	protected abstract ObjectoPersistente convertirAObjeto(ResultSet result);
}
